package multiThread;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <b> 描述:</b> ;<br/>
 *
 * @author <b>作者</b>cdxuhongya@jd.com
 *         <b>时间</b>2017/3/13 15:12<br/>
 *         <b>@CopyRight (c) </b>2015-京东智能版权所有<br/>
 */
public class CyclicBarrierTest {

    public static void main(String[] args) {
        Integer THREAD_NUM = 50;
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        CyclicBarrier cyclicBarrier = new CyclicBarrier(THREAD_NUM/ 5, new Runnable() {
            public void run() {
                /**
                 * 当凑齐后，会调用改方法，也可以默认不传递
                 *
                 * */
                System.out.println("cyclicBarrier working--------------------------");
            }
        });

        for (int i = 0; i < THREAD_NUM; i++) {
            executorService.submit(new MyThread(cyclicBarrier,i));
        }
    }


    public static class MyThread implements Runnable{

        private CyclicBarrier cyclicBarrier;
        private Integer id;
        public MyThread(CyclicBarrier cyclicBarrier,Integer id){
            this.cyclicBarrier = cyclicBarrier;
            this.id = id;
        }
        public void run() {
            try {
                Thread.sleep(new Random(System.currentTimeMillis()).nextInt(1000));
                System.out.println("thread " + id + " is waiting...." + System.currentTimeMillis() / 1000 );
                /**
                 * 当指定数目的线程数倒到改位置后，才会继续往下执行
                 * 可以理解为筹齐7龙珠才能继续向下召唤神龙
                 * */
                cyclicBarrier.await();
                System.out.println("thread " + id + " is working....");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
}



